package com.vmix.android.vmixsdk.rds;

import java.util.ArrayList;

import com.vmix.android.vmixsdk.exception.VmixException;
import com.vmix.android.vmixsdk.valueobject.VmixVideos;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

public class GetCollectionMediasService extends Service {

	public static final String MEDIA_FOUND = "media_found";
	
	protected String collectionId = null;
	protected String formatId = null;
	protected GetCollectionMediasOperation operation = null;
	private VmixVideos videos = null;
	
	private final IBinder binder = new GetCollectionMediasBinder();

	private Thread thread = null;
	
	@Override
	public void onCreate() {
	
		super.onCreate();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return binder;
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		// get access to the intent
		Bundle bundle = intent.getExtras();
		// get collectionId
		this.collectionId = bundle.getString("collectionId");
		this.formatId = bundle.getString("formatId");
		
		this.thread = new Thread( null, this.doBackgroundThreadProcessing, "getCollectionMediasOperationThread");
		
		this.thread.start();

		
		return Service.START_STICKY;
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		this.stopThreads();
	}
	
	/**
	 * public funtion to be accessed by service binders to get the videos back
	 * 
	 * @return ArrayList
	 */
	public VmixVideos getVideos() {
		
		return this.videos;
		
	}

	/**
	 * custom binder for getCollectionsService
	 * 
	 * @author lei
	 *
	 */
	public class GetCollectionMediasBinder extends Binder {
		public GetCollectionMediasService getService() {
			return GetCollectionMediasService.this;
		}
	}
	
	// execute the operation
	private void performGetCollectionMedias() {
		try {
			this.operation = new GetCollectionMediasOperation( this.collectionId, this.formatId );
			
			this.videos = this.operation.process();
			
			this.onLoadComplete();
			
		}
		catch( VmixException e ) {
			//TODO
		}
	}
	
	/**
	 * announce load complete for anyone who listens
	 */
	private void onLoadComplete() {
		// stopping threads
		// this.stopThreads();
		
		// create new intent
		Intent intent = new Intent( GetCollectionMediasService.MEDIA_FOUND );
		
		// broadcast
		sendBroadcast( intent );
	}
	
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
		
			performGetCollectionMedias();
			
		}
		
	};
	
	// stopping all the running threads
	private void stopThreads() {
		
		// stopping
		if( this.thread.isAlive() ) {
		
			this.thread.stop();
		}
	}
	
}
